package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.ReadersService;
import com.joint.base.service.RemindService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.Participant;
import com.joint.core.entity.Summary;
import com.joint.core.entity.Train;
import com.joint.core.entity.TrainRecord;
import com.joint.core.service.SummaryService;
import com.joint.core.service.TrainRecordService;
import com.joint.core.service.TrainService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import javax.persistence.OneToMany;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxSummaryAction extends BaseFlowAction {

    @Resource
    private SummaryService summaryService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private TrainService trainService;
    @Resource
    private TrainRecordService trainRecordService;
    @Resource
    private ReadersService readersService;
    @Resource
    private RemindService remindService;


    private Train train;
    private Summary summary;
    private String name;
    private List<Users> teacherList;
    private Dict type;
    private List<Map<String, Object>> trainDict;
    private String assessmentfileId;
    private String assessmentfileIds;
    private Users loginUser;
    private Users creater;
    private String createDate;
    private int numStatus;
    private String teacherId;
    private String typeDictId;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "summary";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            train= trainService.get(parentId);
            params.put("train",train);
        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=summaryService.findByPagerAndLimit(true, "summary", pager, params);

        List<Summary> tList;
        if (pager.getTotalCount() > 0){
            tList = (List<Summary>) pager.getList();
        }else{
            tList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Summary summary:tList){
            rMap = new HashMap<String,Object>();
            rMap.put("creater",summary.getCreater().getName());
            rMap.put("id",summary.getId());
            rMap.put("time",DataUtil.DateToString(summary.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("state",summary.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);
        //LogUtil.info("dataRows"+dataRows);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * read页面
     */
    public String read(){
        assessmentfileId="";
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            summary=summaryService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            if(summary.getAssessment().size()>0){
                for(FileManage r:summary.getAssessment()){
                    assessmentfileId+=r.getId()+",";
                }
            }
        }

        return "read";
    }

    public String input(){

        assessmentfileId="";
        Company company = usersService.getCompanyByUser();
        trainDict = new ArrayList<Map<String, Object>>();

        Map<String,Object> rMap = null;

        if (StringUtils.isNotEmpty(keyId)){
            summary = summaryService.get(keyId);
            if(summary.getAssessment().size()>0){
                for(FileManage r:summary.getAssessment()){
                    assessmentfileId+=r.getId()+",";
                }
            }
            type=summary.getType();
            name=summary.getName();
            teacherList=summary.getTeacher();
            creater=summary.getCreater();
            createDate= DataUtil.DateToString(summary.getCreateDate(),"yyyy-MM-dd");

        } else {

            if (StringUtils.isNotEmpty(parentId)){
                train= trainService.get(parentId);
                type=train.getType();
                name=train.getName();
                teacherList=train.getTrainUsers();
            }
            loginUser = usersService.getLoginInfo();
            creater=loginUser;
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");

        }

        return "input";
    }

    private void setData(){

        List<FileManage> fileList = Lists.newArrayList();
        List<Department> departmentList = Lists.newArrayList();
        List<Users> usersList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(keyId)){
            summary = summaryService.get(keyId);
        }else{
            summary = new Summary();
            summary.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(assessmentfileIds)){
            for(String r:assessmentfileIds.split(",")){
                fileList.add(fileManageService.get(r.trim()));
            }
        }

        if(StringUtils.isNotEmpty(teacherId)){
            for (String id:teacherId.split(",")){
                usersList.add(usersService.get(id));
            }
        }
        if(StringUtils.isNotEmpty(parentId)){
            summary.setTrain(trainService.get(parentId));

        }

        if(StringUtils.isNotEmpty(typeDictId)){
            summary.setType(dictService.get(typeDictId));
        }

        summary.setTeacher(usersList);
        summary.setName(name);
        summary.setAssessment(fileList);
        summary.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                summaryService.update(summary);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                summaryService.save(summary, "summary", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                summaryService.approve(summary, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId=summaryService.commit(summary, "summary", var1, var2, curDutyId);

                //trainService.commit(train, FlowEnum.ProcessState.Finished,"train", var1,var2, curDutyId);

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        List<Users> usersList= Lists.newArrayList();
        Set<Participant> participantSet = summary.getTrain().getParticipantSet();
        for (Participant participant:participantSet){
            usersList = participant.getParticipantUsers();
            //增加归档后读者
            for(Users users:usersList){
                Readers readers = new Readers();
                readers.setUsers(users);
                readers.setBussinessKey("summary");
                readers.setKeyId(keyId);
                readers.setType(2);
                readersService.save(readers);
            }

            for(Users users:usersList){
                Remind remind = new Remind();
                remind.setUsers(users);
                remind.setBussinessKey("summary");
                remind.setKeyId(keyId);
                remind.setContent("培训已归档");
                remindService.save(remind);
            }

        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 审批
     * @return
     */
    public String approve1(){
        summary = summaryService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                summaryService.approve(summary, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);

                Train train = summary.getTrain();
                Set<Participant> participantSet =train.getParticipantSet();
                List<Users> usersList= Lists.newArrayList();

                for (Participant participant:participantSet){
                    usersList = participant.getParticipantUsers();
                    for(Users users:usersList){
                        TrainRecord trainRecord = new TrainRecord();
                        trainRecord.setUsers(users);
                        trainRecord.setName(train.getName());
                        trainRecord.setType(train.getType().getName());
                        trainRecord.setStartDate(train.getStartDate());
                        trainRecord.setEndDate(train.getEndDate());
                        trainRecordService.save(trainRecord);
                    }

                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public Summary getSummary() {
        return summary;
    }

    public void setSummary(Summary summary) {
        this.summary = summary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Map<String, Object>> getTrainDict() {
        return trainDict;
    }

    public void setTrainDict(List<Map<String, Object>> trainDict) {
        this.trainDict = trainDict;
    }

    public String getAssessmentfileId() {
        return assessmentfileId;
    }

    public void setAssessmentfileId(String assessmentfileId) {
        this.assessmentfileId = assessmentfileId;
    }

    public String getAssessmentfileIds() {
        return assessmentfileIds;
    }

    public void setAssessmentfileIds(String assessmentfileIds) {
        this.assessmentfileIds = assessmentfileIds;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public Users getCreater() {
        return creater;
    }

    public void setCreater(Users creater) {
        this.creater = creater;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }


    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public Train getTrain() {
        return train;
    }

    public void setTrain(Train train) {
        this.train = train;
    }

    public String getTeacherId() {
        return teacherId;
    }

    public void setTeacherId(String teacherId) {
        this.teacherId = teacherId;
    }

    public String getTypeDictId() {
        return typeDictId;
    }

    public void setTypeDictId(String typeDictId) {
        this.typeDictId = typeDictId;
    }

    public List<Users> getTeacherList() {
        return teacherList;
    }

    public void setTeacherList(List<Users> teacherList) {
        this.teacherList = teacherList;
    }

    public Dict getType() {
        return type;
    }

    public void setType(Dict type) {
        this.type = type;
    }
}
